package cn.apthink.calendar;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;

import cn.apthink.utility.Util;
import lombok.Getter;

/**
 * 特殊工作日模板（不支持生产部门继承）
 * @author david
 * @createdate 2024年10月8日
 */
public class SpecialWorkDayHelper {
	@Getter
	private final static Map<String, List<WorkDay>> specialDays = new HashMap<String, List<WorkDay>>();
	
	public void refreshData(List<SpecialWorkDay> lstSpecialDay) {
		if (!Util.isEmpty(lstSpecialDay)) {
			Set<String> departmentIds = lstSpecialDay.stream().map(SpecialWorkDay::getDepartmentId).collect(Collectors.toSet());
			for (String departmentId : departmentIds) {
				List<WorkDay> lstWorkDays = new ArrayList<WorkDay>();
				List<SpecialWorkDay> ds = lstSpecialDay.stream().filter(x->{
					return x.getDepartmentId().equals(departmentId);
				}).collect(Collectors.toList());
				List<LocalDate> lds = ds.stream().map(SpecialWorkDay::getWorkDate).collect(Collectors.toList());
				for (LocalDate d : lds) {
					List<SpecialWorkDay> wds  = ds.stream().filter(x->{
						return x.getWorkDate().equals(d);
					}).collect(Collectors.toList());
					Day day = new Day();
					for (SpecialWorkDay w : wds) {
						TimeRange tr = DayTimeHelper.getTimeRange(w.getStartSecond(), w.getEndSecond(), w.isOvertime());
						day.addTimeRange(tr);
					}
					day = DayTimeHelper.getDay(day);
					WorkDay workDay = new WorkDay(d);
					workDay.setDay(day);
					lstWorkDays.add(workDay);
				}
				specialDays.put(departmentId, lstWorkDays);
			}
		}
	}
	
	/**
	 * 返回WorkDay对象没有设置worker，无法计算capacity
	 * @param departmentId
	 * @param current
	 * @return
	 */
	public WorkDay getWorkDay(String departmentId, LocalDate current) {
		List<WorkDay> lstWorkDay = specialDays.get(departmentId);
		if (!Util.isEmpty(lstWorkDay)) {
			Optional<WorkDay> o = lstWorkDay.stream().filter(x->{
				return x.getCurrent().equals(current);
			}).findAny();
			if (o.isPresent())
				return o.get();
		}
		return null;
	}

}
